﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Cnm.Core;
using Cnm.Core.Caching;
using Cnm.Core.Domain.Localization;
using Cnm.Models.ViewModels;
using Cnm.Mvc.Web.Framework.Localization;
using Cnm.Servicers.Localization;
using Microsoft.Ajax.Utilities;

namespace Cnm.Mvc.Web.Controllers
{
    public partial class CommonController : BasePublicController
    {
        #region Fields

        private readonly ILanguageService _languageService;
        private readonly ICacheManager _cacheManager;
        private readonly IWorkContext _workContext;

        private readonly LocalizationSettings _localizationSettings;

        #endregion

        #region Constructors

        public CommonController(
            ILanguageService languageService,
            ICacheManager cacheManager,
            LocalizationSettings localizationSettings,
            IWorkContext workContext)
        {
            this._languageService = languageService;
            this._cacheManager = cacheManager;
            this._localizationSettings = localizationSettings;
            this._workContext = workContext;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual int GetUnreadPrivateMessages()
        {
            var result = 0;

            return result;
        }

        #endregion

        #region Methods

        //page not found
        public ActionResult PageNotFound()
        {
            this.Response.StatusCode = 404;
            this.Response.TrySkipIisCustomErrors = true;

            return View();
        }

        //language
        [ChildActionOnly]
        public ActionResult LanguageSelector()
        {
            var availableLanguages = _cacheManager.Get("All_Language", () =>
            {
                var result = _languageService
                    .GetAllLanguages()
                    .Select(x => new LanguageModel()
                    {
                        Id = x.Id,
                        Name = x.Name,
                        FlagImageFileName = x.FlagImageFileName,
                    })
                    .ToList();
                return result;
            });

            var model = new LanguageSelectorModel()
            {
                CurrentLanguageId = _workContext.WorkingLanguage.Id,
                AvailableLanguages = availableLanguages,
                UseImages = _localizationSettings.UseImagesForLanguageSelection
            };

            if (model.AvailableLanguages.Count == 1)
                Content("");

            return PartialView(model);
        }
        public ActionResult SetLanguage(int langid, string returnUrl = "")
        {
            var language = _languageService.GetLanguageById(langid);
            if (language.Published != null && (language != null && (bool) language.Published))
            {
                _workContext.WorkingLanguage = language;
            }

            //home page
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = Url.RouteUrl("HomePage");

            //prevent open redirection attack
            if (!Url.IsLocalUrl(returnUrl))
                returnUrl = Url.RouteUrl("HomePage");

            //language part in URL
            if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                string applicationPath = HttpContext.Request.ApplicationPath;
                if (returnUrl.IsLocalizedUrl(applicationPath, true))
                {
                    //already localized URL
                    returnUrl = returnUrl.RemoveLanguageSeoCodeFromRawUrl(applicationPath);
                }

                returnUrl = returnUrl.AddLanguageSeoCodeToRawUrl(applicationPath, _workContext.WorkingLanguage);
            }
            return Redirect(returnUrl);
        }

        
        //sitemap page
        public ActionResult Sitemap()
        {
            //if (!_commonSettings.SitemapEnabled)
            //    return RedirectToRoute("HomePage");

            //var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles
            //   .Where(cr => cr.Active).Select(cr => cr.Id).ToList();
            //string cacheKey = string.Format(ModelCacheEventConsumer.SITEMAP_PAGE_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id);
            //var cachedModel = _cacheManager.Get(cacheKey, () =>
            //{
            //    var model = new SitemapModel()
            //    {
            //        BlogEnabled = _blogSettings.Enabled,
            //        ForumEnabled = _forumSettings.ForumsEnabled,
            //        NewsEnabled = _newsSettings.Enabled,
            //    };
            //    if (_commonSettings.SitemapIncludeCategories)
            //    {
            //        var categories = _categoryService.GetAllCategories();
            //        model.Categories = categories.Select(x => x.ToModel()).ToList();
            //    }
            //    if (_commonSettings.SitemapIncludeManufacturers)
            //    {
            //        var manufacturers = _manufacturerService.GetAllManufacturers();
            //        model.Manufacturers = manufacturers.Select(x => x.ToModel()).ToList();
            //    }
            //    if (_commonSettings.SitemapIncludeProducts)
            //    {
            //        //limit product to 200 until paging is supported on this page
            //        var products = _productService.SearchProducts(storeId: _storeContext.CurrentStore.Id,
            //            visibleIndividuallyOnly: true,
            //            pageSize: 200);
            //        model.Products = products.Select(product => new ProductOverviewModel()
            //        {
            //            Id = product.Id,
            //            Name = product.GetLocalized(x => x.Name),
            //            ShortDescription = product.GetLocalized(x => x.ShortDescription),
            //            FullDescription = product.GetLocalized(x => x.FullDescription),
            //            SeName = product.GetSeName(),
            //        }).ToList();
            //    }
            //    if (_commonSettings.SitemapIncludeTopics)
            //    {
            //        var topics = _topicService.GetAllTopics(_storeContext.CurrentStore.Id)
            //            .ToList()
            //            .FindAll(t => t.IncludeInSitemap);
            //        model.Topics = topics.Select(topic => new TopicModel()
            //        {
            //            Id = topic.Id,
            //            SystemName = topic.SystemName,
            //            IncludeInSitemap = topic.IncludeInSitemap,
            //            IsPasswordProtected = topic.IsPasswordProtected,
            //            Title = topic.GetLocalized(x => x.Title),
            //        })
            //        .ToList();
            //    }
            //    return model;
            //});

            //return View(cachedModel);
            return View();
        }

        //SEO sitemap page
        public ActionResult SitemapXml()
        {
            //if (!_commonSettings.SitemapEnabled)
            //    return RedirectToRoute("HomePage");

            //var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles
            //  .Where(cr => cr.Active).Select(cr => cr.Id).ToList();
            //string cacheKey = string.Format(ModelCacheEventConsumer.SITEMAP_SEO_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id);
            //var siteMap = _cacheManager.Get(cacheKey, () =>
            //{
            //    return _sitemapGenerator.Generate(this.Url);
            //});
            //return Content(siteMap, "text/xml");
            return View();
        }

        public ActionResult GenericUrl()
        {
            //seems that no entity was found
            return InvokeHttp404();
        }

        //store is closed
        public ActionResult StoreClosed()
        {
            return View();
        }

        #endregion
    }
}